<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!--
          Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮
         -->
    <form class="search-form" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText"></search-result>
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></search-suggestion>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      @search="onSearch"
      @deleteBtn="searchHistories = []"
      :searchHistories="searchHistories"
      v-else
    ></search-history>
    <!-- /搜索历史记录 -->
  </div>
</template>
<script>
import { getItem, setItem } from '@/utils/storage'
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion.vue'

export default {
  name: 'SearchPage',
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion,
  },
  props: {},
  data() {
    return {
      searchText: '', // 输入框绑定的数据
      isResultShow: false, // 搜索结果是否展示

      searchHistories: getItem('SERACH_HISTORY') || [],
    }
  },
  computed: {},
  watch: {
    searchHistories(val) {
      setItem('SERACH_HISTORY', val)
    },
  },
  created() {},
  methods: {
    onSearch(val) {
      console.log('确定了')
      console.log(val)
      // 显示搜索结果
      this.searchText = val
      const index = this.searchHistories.indexOf(val)

      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }

      this.searchHistories.unshift(val)

      this.isResultShow = true
    },

    //   取消事件   【点击了取消按钮或者关闭图标】

    onCancel() {
      this.$router.back()
    },
  },
}
</script>
<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>